import { createRouter, createWebHistory } from 'vue-router';
import { roleVerify} from '@/api/auth';


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component:()=>import ('@/views/Home.vue'),
      children: [
        {
          path:'',
          name:'homeMain',
          component:() => import('@/views/HomePage/homeMain.vue'),
        },
        {
          path:'flowerKnowledge',
          name:'flowerKnowledge',
          component:() => import("@/views/HomePage/flowerKnowledge.vue")
        },
        {
          path:'Item',
          name:'Item',
          component:() => import("@/views/HomePage/Item.vue")
        },
        {
          path:'ItemDetail',
          name:'ItemDetail',
          component:() => import("@/components/front/Item_detail.vue")
        },
        {
          path:'Article',
          name:'Article',
          component:() => import("@/views/HomePage/Article.vue")
        },
        {
          path:'/article/:id',
          name:'ArticleDetail',
          component:() => import("@/views/HomePage/ArticleDetail.vue"),
        },
        {
          path:'Order',
          name:'Order',
          component:() => import("@/views/HomePage/Order.vue")
        },
        {
          path:'Cart',
          name:'Cart',
          component:() => import("@/views/HomePage/Cart.vue")
        },
      ]
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component:()=> import('@/views/AboutView.vue')
    },
    {
      //后台页面
      path:'/backend',
      name:'backend',
      component:()=> import('@/views/backend/backendIndex.vue'),
      meta:{
        auth:true
      }
    },
    {
      //后台登录
      path:'/backendLogin',
      name:'backendLogin',
      component:()=> import('@/views/backend/backendLogin.vue')
    },
    {
      //前台登录注册页面
      path:'/login',
      name:'login',
      component:()=> import('@/views/front/login.vue')
    },
    {
      //前台密码重置页面
      path:'/passwordResetting',
      name:'passwordResetting',
      component:()=> import('@/views/front/PasswordResetting.vue')
    }
  ]
})

export default router

router.beforeEach(async (to, from, next) => {
  if (to.matched.some(record => record.meta.auth) && to.meta.auth) { // 判断该路由是否需要登录权限
    let token = localStorage.getItem('token');
    if (token) { // 获取当前的 token 是否存在
   await roleVerify().then((response) => {
      if (response.data.data==true){
        next()
      }else{
        //权限不够。跳回主页
        next({
          path: '/'
        })
      }
    })
    .catch((error) => {
      next({
        path: '/'
      })
    })
    } else {
      // 不存在 token，需要重新认证
      next({
        path: '/login'
      })
    }
  }
  next();
});
